package com.servertest1;


import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Login extends FragmentActivity {

	private Client client;

	private DatabaseHelper checker;
	private MainFragment mainFragment;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);

		setContentView(R.layout.blank);
		client = new Client();
		checker = new DatabaseHelper(this);
		if(!checker.isEmpty()){
			String[] cmd = new String[3];
			cmd[0] = "login";
			cmd[1] = checker.getUser();
			cmd[2] = "auto_login";

			new loginTask().execute(cmd);
		}

		else{
			if (savedInstanceState == null) {
				// Add the fragment on initial activity setup
				mainFragment = new MainFragment();
				getSupportFragmentManager()
				.beginTransaction()
				.add(android.R.id.content, mainFragment)
				.commit();
			} 
			else {
				// Or set the fragment from restored state info
				mainFragment = (MainFragment) getSupportFragmentManager()
						.findFragmentById(android.R.id.content);
			}



		}
		checker.close();

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		System.out.println("CLOSING NOW!!!!");
		if (checker != null) {
			checker.close();
		}
	}

	public class loginTask extends AsyncTask<String, Void, String[]>{
		protected String[] doInBackground(String... cmd){

			client.connect();
			System.out.println("after");
			client.sendData(cmd);
			String[] result = client.recieveData();
			client.close();


			return result;

		}

		protected void onPostExecute(String[] result){


			if(result[0].equals("auto_success")){
				Intent myIntent = new Intent(Login.this, Menu.class);
				myIntent.putExtra("gameData", result);
				Login.this.startActivity(myIntent);
				finish();
			}
			else if(result[0].equals("account_does_not_exist")){
				Toast.makeText(Login.this, "This account does not exist", Toast.LENGTH_LONG).show(); 
			}
			else if(result[0].equals("account_does_not_exist_auto_login")){
				//TODO: Database problem here still doesn't work!
				checker = new DatabaseHelper(Login.this);
				checker.deleteAll();
				Intent myIntent = new Intent(Login.this, Login.class);
				Login.this.startActivity(myIntent);
				finish();
			}
			else{
				Toast.makeText(Login.this, "An unexpected error has occured.", Toast.LENGTH_LONG).show();
			}
		}		
	}
}